<template>
  <div class="page-container">
    <div class="thesis-management">
      <header class="header">
        <div class="title-section">
          <h1 class="main-title">结题助手</h1>
          <span class="sub-title">管理资料</span>
        </div>
        <router-link to="/main/add/longitudinal" class="add-button">
          <Plus class="icon" />
          添加新课题
        </router-link>
      </header>

      <div v-if="loading" class="loading-container">
        加载中...
      </div>
      <div v-else-if="thesisList.length === 0" class="empty-container">
        <div class="empty-content">
          <FileText class="empty-icon" />
          <p class="empty-text">暂无课题数据</p>
          <p class="empty-desc">请添加成果并关联纵向课题</p>
        </div>
      </div>
      <div v-else class="table-container">
        <table class="thesis-table">
          <thead>
          <tr>
            <th>课题名称</th>
            <th>开始时间</th>
            <th>课程级别</th>
            <th>课程状态</th>
            <th>相关成果</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <template v-for="thesis in thesisList" :key="thesis.id">
            <tr>
              <td>
                <div class="thesis-name">
                  <FileText class="doc-icon" />
                  {{ thesis.name }}
                </div>
              </td>
              <td>{{ formatDate(thesis.startDate) }}</td>
              <td>{{ thesis.level }}</td>
              <td>{{ thesis.status }}</td>
              <td>
                <a class="link-text" @click="toggleResults(thesis)">
                  {{ thesis.resultCount }}个成果 查看或添加
                </a>
              </td>
              <td>
                <button class="preview-button" @click="previewMaterials(thesis)">
                  预览结题材料
                </button>
              </td>
            </tr>
            <!-- 展开的相关成果面板 -->
            <tr v-if="thesis.showResults" class="results-panel">
              <td colspan="6">
                <div class="results-container">
                  <!-- 相关论文 -->
                  <div class="result-section">
                    <div class="result-header">
                      <h3>相关论文</h3>
                    </div>
                    <div v-if="getResultsByType(thesis, '相关论文').length" class="result-items">
                      <div v-for="(paper, index) in getResultsByType(thesis, '相关论文')"
                           :key="paper.id"
                           class="result-item">
                        <span class="item-name">{{ paper.title }}</span>
                        <div class="item-actions">
                          <button @click="moveItem('up', '相关论文', index, thesis)"
                                  :disabled="index === 0">上移</button>
                          <button @click="moveItem('down', '相关论文', index, thesis)"
                                  :disabled="index === getResultsByType(thesis, '相关论文').length - 1">下移</button>
                          <button @click="removeItem('相关论文', index, thesis)">移除</button>
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-result-item">
                      <span>暂无相关论文</span>
                    </div>
                  </div>

                  <!-- 相关专利 -->
                  <div class="result-section">
                    <div class="result-header">
                      <h3>相关专利</h3>
                    </div>
                    <div v-if="getResultsByType(thesis, '相关专利').length" class="result-items">
                      <div v-for="(patent, index) in getResultsByType(thesis, '相关专利')"
                           :key="patent.id"
                           class="result-item">
                        <span class="item-name">{{ patent.title }}</span>
                        <div class="item-actions">
                          <button @click="moveItem('up', '相关专利', index, thesis)"
                                  :disabled="index === 0">上移</button>
                          <button @click="moveItem('down', '相关专利', index, thesis)"
                                  :disabled="index === getResultsByType(thesis, '相关专利').length - 1">下移</button>
                          <button @click="removeItem('相关专利', index, thesis)">移除</button>
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-result-item">
                      <span>暂无相关专利</span>
                    </div>
                  </div>

                  <!-- 相关个人获奖 -->
                  <div class="result-section">
                    <div class="result-header">
                      <h3>相关个人获奖</h3>
                    </div>
                    <div v-if="getResultsByType(thesis, '相关个人获奖').length" class="result-items">
                      <div v-for="(award, index) in getResultsByType(thesis, '相关个人获奖')"
                           :key="award.id"
                           class="result-item">
                        <span class="item-name">{{ award.title }}</span>
                        <div class="item-actions">
                          <button @click="moveItem('up', '相关个人获奖', index, thesis)"
                                  :disabled="index === 0">上移</button>
                          <button @click="moveItem('down', '相关个人获奖', index, thesis)"
                                  :disabled="index === getResultsByType(thesis, '相关个人获奖').length - 1">下移</button>
                          <button @click="removeItem('相关个人获奖', index, thesis)">移除</button>
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-result-item">
                      <span>暂无相关个人获奖</span>
                    </div>
                  </div>

                  <!-- 相关媒体报道 -->
                  <div class="result-section">
                    <div class="result-header">
                      <h3>相关媒体报道</h3>
                    </div>
                    <div v-if="getResultsByType(thesis, '相关媒体报道').length" class="result-items">
                      <div v-for="(media, index) in getResultsByType(thesis, '相关媒体报道')"
                           :key="media.id"
                           class="result-item">
                        <span class="item-name">{{ media.title }}</span>
                        <div class="item-actions">
                          <button @click="moveItem('up', '相关媒体报道', index, thesis)"
                                  :disabled="index === 0">上移</button>
                          <button @click="moveItem('down', '相关媒体报道', index, thesis)"
                                  :disabled="index === getResultsByType(thesis, '相关媒体报道').length - 1">下移</button>
                          <button @click="removeItem('相关媒体报道', index, thesis)">移除</button>
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-result-item">
                      <span>暂无相关媒体报道</span>
                    </div>
                  </div>

                  <!-- 相关著作权 -->
                  <div class="result-section">
                    <div class="result-header">
                      <h3>相关著作权</h3>
                    </div>
                    <div v-if="getResultsByType(thesis, '相关著作权').length" class="result-items">
                      <div v-for="(copyright, index) in getResultsByType(thesis, '相关著作权')"
                           :key="copyright.id"
                           class="result-item">
                        <span class="item-name">{{ copyright.title }}</span>
                        <div class="item-actions">
                          <button @click="moveItem('up', '相关著作权', index, thesis)"
                                  :disabled="index === 0">上移</button>
                          <button @click="moveItem('down', '相关著作权', index, thesis)"
                                  :disabled="index === getResultsByType(thesis, '相关著作权').length - 1">下移</button>
                          <button @click="removeItem('相关著作权', index, thesis)">移除</button>
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-result-item">
                      <span>暂无相关著作权</span>
                    </div>
                  </div>

                  <!-- 相关学生获奖 -->
                  <div class="result-section">
                    <div class="result-header">
                      <h3>相关学生获奖</h3>
                    </div>
                    <div v-if="getResultsByType(thesis, '相关学生获奖').length" class="result-items">
                      <div v-for="(award, index) in getResultsByType(thesis, '相关学生获奖')"
                           :key="award.id"
                           class="result-item">
                        <span class="item-name">{{ award.title }}</span>
                        <div class="item-actions">
                          <button @click="moveItem('up', '相关学生获奖', index, thesis)"
                                  :disabled="index === 0">上移</button>
                          <button @click="moveItem('down', '相关学生获奖', index, thesis)"
                                  :disabled="index === getResultsByType(thesis, '相关学生获奖').length - 1">下移</button>
                          <button @click="removeItem('相关学生获奖', index, thesis)">移除</button>
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-result-item">
                      <span>暂无相关学生获奖</span>
                    </div>
                  </div>

                  <!-- 相关继续教育材料 -->
                  <div class="result-section">
                    <div class="result-header">
                      <h3>相关继续教育材料</h3>
                    </div>
                    <div v-if="getResultsByType(thesis, '相关继续教育材料').length" class="result-items">
                      <div v-for="(edu, index) in getResultsByType(thesis, '相关继续教育材料')"
                           :key="edu.id"
                           class="result-item">
                        <span class="item-name">{{ edu.title }}</span>
                        <div class="item-actions">
                          <button @click="moveItem('up', '相关继续教育材料', index, thesis)"
                                  :disabled="index === 0">上移</button>
                          <button @click="moveItem('down', '相关继续教育材料', index, thesis)"
                                  :disabled="index === getResultsByType(thesis, '相关继续教育材料').length - 1">下移</button>
                          <button @click="removeItem('相关继续教育材料', index, thesis)">移除</button>
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-result-item">
                      <span>暂无相关继续教育材料</span>
                    </div>
                  </div>

                  <!-- 相关著作 -->
                  <div class="result-section">
                    <div class="result-header">
                      <h3>相关著作</h3>
                    </div>
                    <div v-if="getResultsByType(thesis, '相关著作').length" class="result-items">
                      <div v-for="(pub, index) in getResultsByType(thesis, '相关著作')"
                           :key="pub.id"
                           class="result-item">
                        <span class="item-name">{{ pub.title }}</span>
                        <div class="item-actions">
                          <button @click="moveItem('up', '相关著作', index, thesis)"
                                  :disabled="index === 0">上移</button>
                          <button @click="moveItem('down', '相关著作', index, thesis)"
                                  :disabled="index === getResultsByType(thesis, '相关著作').length - 1">下移</button>
                          <button @click="removeItem('相关著作', index, thesis)">移除</button>
                        </div>
                      </div>
                    </div>
                    <div v-else class="empty-result-item">
                      <span>暂无相关著作</span>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </template>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, FileText } from 'lucide-vue-next'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCompletedLongitudinalsForSolution } from "@/api/Research/Longitudinal.js"

const thesisList = ref([])
const loading = ref(true)
const router = useRouter()

// 获取课题列表
const fetchThesisList = async () => {
  loading.value = true
  try {
    const response = await getCompletedLongitudinalsForSolution()
    if (response.code === 1) {
      thesisList.value = response.data.map((item) => ({
        id: item.projectNumber,
        name: item.projectName,
        startDate: item.startTime,
        level: item.projectLevel,
        status: item.projectStatus,
        resultCount: item.relatedResultsCount,
        showResults: false,
        results: item.resultsCountVO || [] // 存储所有相关成果
      }))
    } else {
      ElMessage.error('获取课题列表失败：' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取课题列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 根据类型获取成果列表
const getResultsByType = (thesis, type) => {
  return thesis.results.filter(result => result.type === type)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-')
}

// 切换显示相关成果
const toggleResults = (thesis) => {
  thesis.showResults = !thesis.showResults
}

const previewMaterials = (thesis) => {
  // 检查是否所有结果都有PDF路径
  const missingPdfResults = thesis.results.filter(result => !result.pdfPath && !result.pdfUrl)

  if (missingPdfResults.length > 0) {
    // 有结果缺少PDF路径
    const missingTitles = missingPdfResults.map(result => result.title).join(', ');

    // 弹出警告框，用户必须关闭后才能继续操作
    ElMessageBox.alert(
        `以下材料缺少PDF文件，请选择上传或移除相关材料：\n${missingTitles}`,
        '警告',
        {
          confirmButtonText: '返回修改',
          type: 'warning'
        }
    );
  } else {
    // 所有结果都有PDF路径，直接预览
    navigateToPreview(thesis);
  }


}

const navigateToPreview = (thesis) => {
  console.log('navigateToPreview', thesis);
  router.push({
    path: '/academic/material',
    params: { id: thesis.id },
    query: {
      projectName: thesis.name,
      projectLevel: thesis.level,
      projectNumber: thesis.id,
      startTime: thesis.startDate,
      projectStatus: thesis.status,
      results: JSON.stringify(thesis.results)
    }
  })
}

// 添加相关成果
const addResult = (type, thesis) => {
  router.push({
    path: `/add-result/${type}`,
    query: { thesisId: thesis.id }
  })
}

// 移动项目
const moveItem = (direction, type, index, thesis) => {
  const items = getResultsByType(thesis, type)
  if (direction === 'up' && index > 0) {
    const temp = thesis.results.findIndex(r => r === items[index])
    const prevTemp = thesis.results.findIndex(r => r === items[index - 1])
    ;[thesis.results[temp], thesis.results[prevTemp]] = [thesis.results[prevTemp], thesis.results[temp]]
  } else if (direction === 'down' && index < items.length - 1) {
    const temp = thesis.results.findIndex(r => r === items[index])
    const nextTemp = thesis.results.findIndex(r => r === items[index + 1])
    ;[thesis.results[temp], thesis.results[nextTemp]] = [thesis.results[nextTemp], thesis.results[temp]]
  }
}

// 移除项目
const removeItem = (type, index, thesis) => {
  ElMessageBox.confirm('确定要移除该项目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const items = getResultsByType(thesis, type)
    const targetIndex = thesis.results.findIndex(r => r === items[index])
    if (targetIndex > -1) {
      thesis.results.splice(targetIndex, 1)
      thesis.resultCount = thesis.results.length
      ElMessage.success('移除成功')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchThesisList()
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
  display: flex;
  justify-content: center;
}

.thesis-management {
  width: 100%;
  max-width: 1200px;
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.title-section {
  display: flex;
  align-items: baseline;
  gap: 12px;
}

.main-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.nowrap-title {
  white-space: nowrap; /* 禁止自动换行 */
  overflow: visible;  /* 溢出内容不隐藏 */
  text-overflow: clip; /* 不显示省略号 */
}

.sub-title {
  color: #666;
  font-size: 14px;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  background-color: #fff;
  border: 1px solid #1890ff;
  color: #1890ff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  text-decoration: none;
}

.add-button:hover {
  background-color: #e6f7ff;
}

.icon {
  width: 16px;
  height: 16px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.thesis-table {
  width: 100%;
  table-layout: auto;
  border-collapse: collapse;
}

.thesis-table th,
.thesis-table td {
  padding: 16px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.thesis-table th {
  background-color: #fafafa;
  font-weight: 500;
}

.thesis-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.doc-icon {
  width: 16px;
  height: 16px;
  color: #666;
}

.link-text {
  color: #1890ff;
  cursor: pointer;
}

.link-text:hover {
  text-decoration: underline;
}

.preview-button {
  padding: 6px 16px;
  background-color: #00b96b;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.preview-button:hover {
  background-color: #00a15c;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  font-size: 18px;
  color: #1890ff;
}

.results-panel {
  background-color: #fafafa;
}

.results-container {
  padding: 20px;
}

.result-section {
  margin-bottom: 24px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-header h3 {
  font-size: 16px;
  margin: 0;
  color: #333;
}

.result-items {
  background-color: white;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.result-item:last-child {
  border-bottom: none;
}

.item-name {
  flex: 1;
  margin-right: 16px;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.item-actions button {
  padding: 4px 8px;
  background-color: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.item-actions button:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.item-actions button:disabled {
  color: #d9d9d9;
  border-color: #d9d9d9;
  cursor: not-allowed;
}

/* 空数据状态样式 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.empty-icon {
  width: 64px;
  height: 64px;
  color: #d9d9d9;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  color: #333;
  margin: 8px 0;
}

.empty-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 24px;
}

.empty-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  text-decoration: none;
}

.empty-button:hover {
  background-color: #40a9ff;
}

.empty-result-item {
  padding: 16px;
  text-align: center;
  color: #999;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}
</style>
